package com.rc.gcm;

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.AudioManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.rc.activity.DashBoardScreen;
import com.rc.activity.R;
import com.rc.activity.dao.tbl_Item;
import com.rc.activity.dao.tbl_ItemDao;
import com.rc.activity.dao.tbl_Receipt;
import com.rc.activity.dao.tbl_ReceiptDao;
import com.rc.activity.dao.tbl_Report;
import com.rc.activity.dao.tbl_ReportDao;
import com.rc.activity.dao.tbl_Trip;
import com.rc.activity.dao.tbl_TripDao;
import com.rc.activity.dao.tbl_UserDao;
import com.rc.activity.provider.Contract;
import com.rc.db.DatabaseSupport;
import com.rc.net.NetSupport;
import com.rc.util.Const;

public class GcmIntentService extends IntentService {
	public static final int NOTIFICATION_ID = 1;
	private NotificationManager mNotificationManager;
	NotificationCompat.Builder builder;

	public GcmIntentService() {
		super("GcmIntentService");
	}

	private String TAG = "TAG";

	@Override
	protected void onHandleIntent(Intent intent) {
		Bundle extras = intent.getExtras();
		GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
		// The getMessageType() intent parameter must be the intent you received
		// in your BroadcastReceiver.
		String messageType = gcm.getMessageType(intent);

		if (!extras.isEmpty()) { // has effect of unparcelling Bundle
			/*
			 * Filter messages based on message type. Since it is likely that
			 * GCM will be extended in the future with new message types, just
			 * ignore any message types you're not interested in, or that you
			 * don't recognize.
			 */
			if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR
					.equals(messageType)) {
				controller("Send error: " + extras.toString());
			} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED
					.equals(messageType)) {
				controller("Deleted messages on server: " + extras.toString());
				// If it's a regular GCM message, do some work.
			} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
					.equals(messageType)) {
				// This loop represents the service doing some work.
				for (int i = 0; i < 5; i++) {
					Log.i(TAG,
							"Working... " + (i + 1) + "/5 @ "
									+ SystemClock.elapsedRealtime());
					try {
						Thread.sleep(5000);
					} catch (InterruptedException e) {
					}
				}
				Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
				// Post notification of received message.

				controller(extras.getString("message"));
				Log.i(TAG, "Received: " + extras.toString());
			}
		}
		// Release the wake lock provided by the WakefulBroadcastReceiver.
		GcmBroadcastReceiver.completeWakefulIntent(intent);
	}

	// Put the message into a notification and post it.
	// This is just one simple example of what you might choose to do with
	// a GCM message.
	private void sendNotification(String msg) {

		mNotificationManager = (NotificationManager) this
				.getSystemService(Context.NOTIFICATION_SERVICE);
		mNotificationManager.cancel(NOTIFICATION_ID);
		Intent it = new Intent(this, DashBoardScreen.class);
		it.putExtra(DashBoardScreen.EXTRA_MESSAGE, msg);
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0, it, 0);

		NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
				this).setSmallIcon(R.drawable.ic_noti)
				.setContentTitle(getString(R.string.app_name))
				.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
				.setAutoCancel(true).setOngoing(true).setContentText(msg);

		AudioManager myAudioManager;
		myAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		mBuilder.setContentIntent(contentIntent);
		mBuilder.setAutoCancel(true);
		myAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
		mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
	}

	private void controller(String msg) {
		Cursor cursor = this.getContentResolver().query(
				Contract.CONTENT_URI_USER, null, null, null, null);
		while (cursor.moveToNext()) {
			Const.AUTHENKEY = cursor.getString(cursor
					.getColumnIndex(tbl_UserDao.Properties.Token.columnName));
		}
		cursor.close();
		// get ID Push
		String[] lText = null;
		String mID = "";
		if (msg.indexOf(":") > 0) {
			lText = msg.split(":");
			if (lText.length == 3) {
				mID = lText[2];
			}
		}
		if (mID.equals("")) {
			return;
		}
		lText = null;
		if (mID.indexOf(",") != -1) {

			lText = mID.split(",");
		}
		if (lText != null) {
			for (String mId : lText) {
				callServiceGCM(msg, mId);
			}
		} else {
			callServiceGCM(msg, mID);
		}

	}

	private void callServiceGCM(String msg, String mID) {
		// push Item
		if (msg.indexOf("I") == 0) {

			if (msg.indexOf("C") == -1) {
				tbl_Item objItem = new tbl_Item();
				objItem = DatabaseSupport.getItemsByItemsID(Long.valueOf(mID),
						getApplication());
				if (objItem == null) {
					return;
				}
			}

			if (msg.indexOf("U") == 2) {
				// update Item
				new insertItem().execute(mID);
			}
			if (msg.indexOf("D") == 2) {
				// TODO delete Item
				new deleteItem().execute(mID);
			}
			if (msg.indexOf("C") == 2) {
				// create Item
				new insertItem().execute(mID);
			}
		}

		// push Receipt
		if (msg.indexOf("R") == 0) {
			tbl_Receipt objReceipt = new tbl_Receipt();
			if (msg.indexOf("C") == -1) {
				objReceipt = DatabaseSupport.getReceiptByID(Long.valueOf(mID),
						getApplication());
				if (objReceipt == null) {
					return;
				}
			}
			if (msg.indexOf("U") == 2) {
				// update Receipt
				new updateReceipt().execute(mID);
			}
			if (msg.indexOf("D") == 2) {
				// delete Receipt
				new deleteReceipt().execute(mID);
			}
			if (msg.indexOf("C") == 2) {
				// Insert receipt
				new insertReceipt().execute(mID);

			}
		}

		// push Trip
		if (msg.indexOf("T") == 0) {
			tbl_Trip objTrip = new tbl_Trip();
			if (msg.indexOf("C") == -1) {
				objTrip = DatabaseSupport.getTripByID(Long.valueOf(mID),
						getApplication());
				if (objTrip == null) {
					return;
				}

			}
			if (msg.indexOf("U") == 2) {
				// update Trip
				new insertTrip().execute(mID);
			}
			if (msg.indexOf("D") == 2) {
				// delete Trip
				new deleteTrip().execute(mID);
			}
			if (msg.indexOf("C") == 2) {
				// create Trip
				new insertTrip().execute(mID);
			}
		}

		// push Report
		if (msg.indexOf("P") == 0) {
			tbl_Report objReport = new tbl_Report();
			if (msg.indexOf("C") == -1) {
				objReport = DatabaseSupport.getReportByID(Long.valueOf(mID),
						getApplication());
				if (objReport == null) {
					return;
				}
			}
			if (msg.indexOf("U") == 2) {
				// update Report
				new insertReport().execute(mID);
			}
			if (msg.indexOf("D") == 2) {
				// delete Report
				new deleteReport().execute(mID);
			}
			if (msg.indexOf("C") == 2) {
				// create Report
				new insertReport().execute(mID);
			}
		}
	}

	/**
	 * Insert Receipt server
	 */

	private class insertReceipt extends AsyncTask<String, Void, Boolean> {

		protected Boolean doInBackground(String... urls) {
			return NetSupport.insert_Update_Receipt_by_ID(urls[0],
					getApplicationContext());
		}

		protected void onPostExecute(Boolean isTrue) {
			if (isTrue) {
				Intent i = new Intent("update.receipt");
				sendBroadcast(i);
				sendNotification(getString(R.string.your_receipt_is_converted_successfully));
			}
		}
	}

	/**
	 * Delete Receipt server
	 */
	private class deleteReceipt extends AsyncTask<String, Void, Integer> {

		protected Integer doInBackground(String... urls) {
			return getApplicationContext().getContentResolver().delete(
					Contract.CONTENT_URI_RECEIPT,
					tbl_ReceiptDao.Properties.ReceiptID.columnName + " = "
							+ urls[0], null);

		}

		protected void onPostExecute(Integer isTrue) {
			Intent i = new Intent("update.receipt");
			sendBroadcast(i);
		}
	}

	/**
	 * Delete Receipt server
	 */
	private class deleteTrip extends AsyncTask<String, Void, Integer> {

		protected Integer doInBackground(String... urls) {
			return getApplicationContext().getContentResolver().delete(
					Contract.CONTENT_URI_TRIP,
					tbl_TripDao.Properties.TripID.columnName + " = " + urls[0],
					null);

		}

		protected void onPostExecute(Integer isTrue) {
			Intent i = new Intent("update.trip");
			sendBroadcast(i);
		}
	}

	/**
	 * Update Receipt server
	 */
	private class updateReceipt extends AsyncTask<String, Void, Boolean> {

		protected Boolean doInBackground(String... urls) {
			return NetSupport.insert_Update_Receipt_by_ID(urls[0],
					getApplicationContext());
		}

	}

	/**
	 * Delete Receipt server
	 */
	private class deleteReport extends AsyncTask<String, Void, Integer> {

		protected Integer doInBackground(String... urls) {
			return getApplicationContext().getContentResolver().delete(
					Contract.CONTENT_URI_REPORT,
					tbl_ReportDao.Properties.ReportID.columnName + " = "
							+ urls[0], null);

		}

		protected void onPostExecute(Integer isTrue) {
			Intent i = new Intent("update.report");
			sendBroadcast(i);
		}
	}

	/**
	 * Delete Items server
	 */
	private class deleteItem extends AsyncTask<String, Void, Integer> {

		protected Integer doInBackground(String... urls) {
			return getApplicationContext().getContentResolver().delete(
					Contract.CONTENT_URI_ITEMS,
					tbl_ItemDao.Properties.ItemID.columnName + " = " + urls[0],
					null);

		}

		protected void onPostExecute(Integer isTrue) {

		}
	}

	/**
	 * Insert Items server
	 */

	private class insertItem extends AsyncTask<String, Void, Boolean> {

		protected Boolean doInBackground(String... urls) {
			return NetSupport.insert_Update_Item_by_ID(urls[0],
					getApplicationContext());
		}

		protected void onPostExecute(Boolean isTrue) {

		}
	}

	/**
	 * Insert Items server
	 */

	private class insertTrip extends AsyncTask<String, Void, Boolean> {

		protected Boolean doInBackground(String... urls) {
			return NetSupport.insert_Update_Trip_by_ID(urls[0],
					getApplicationContext());
		}

		protected void onPostExecute(Boolean isTrue) {
			Intent i = new Intent("update.trip");
			sendBroadcast(i);
		}
	}

	/**
	 * Insert Items server
	 */

	private class insertReport extends AsyncTask<String, Void, String> {

		protected String doInBackground(String... urls) {
			return NetSupport.insert_Update_Report_by_ID(urls[0],
					getApplicationContext());
		}

		protected void onPostExecute(String result) {
			sendNotification(result);
			Intent i = new Intent("update.report");
			sendBroadcast(i);
		}
	}

}
